// lib/views/buy_conditions/buy_condition_form.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:drift/drift.dart' as drift;
import 'package:stock_helper/data/datasource/local/database.dart';

import '../controllers/buy_conditions_controller.dart';


class BuyConditionForm extends StatefulWidget {
  final BuyCondition? condition;

  const BuyConditionForm({super.key, this.condition});

  @override
  State<BuyConditionForm> createState() => _BuyConditionFormState();
}

class _BuyConditionFormState extends State<BuyConditionForm> {
  final _formKey = GlobalKey<FormState>();
  final _controller = Get.find<BuyConditionsController>();
  final RxBool _isLoading = false.obs;

  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _recentChangeController = TextEditingController();
  final TextEditingController _epsController = TextEditingController();
  final TextEditingController _navpsController = TextEditingController();
  final TextEditingController _capitalReserveController = TextEditingController();
  final TextEditingController _attentionLevelController = TextEditingController();
  DateTime? _listingDate;
  final AppDatabase database = Get.find<AppDatabase>();

  @override
  void initState() {
    super.initState();
    if (widget.condition != null) {
      _nameController.text = widget.condition!.conditionName;
      _recentChangeController.text = widget.condition!.recentChange?.toString() ?? '';
      _epsController.text = widget.condition!.eps?.toString() ?? '';
      _navpsController.text = widget.condition!.navps?.toString() ?? '';
      _capitalReserveController.text = widget.condition!.capitalReserve?.toString() ?? '';
      _attentionLevelController.text = widget.condition!.attentionLevel?.toString() ?? '';
      _listingDate = widget.condition!.listingDate;
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _recentChangeController.dispose();
    _epsController.dispose();
    _navpsController.dispose();
    _capitalReserveController.dispose();
    _attentionLevelController.dispose();
    super.dispose();
  }

  Future<void> _saveCondition() async {
    if (_formKey.currentState!.validate()) {
      _isLoading.value = true;

      try {
        if (widget.condition == null) {
          // 添加新条件
          final companion = database.createBuyConditionCompanion(
            conditionName: _nameController.text,
            listingDate: _listingDate,
            recentChange: double.tryParse(_recentChangeController.text),
            eps: double.tryParse(_epsController.text),
            navps: double.tryParse(_navpsController.text),
            capitalReserve: double.tryParse(_capitalReserveController.text),
            attentionLevel: int.tryParse(_attentionLevelController.text),
          );
          await _controller.addBuyCondition(companion);

          // 显示成功消息并立即关闭页面
          Get.back();
          Get.snackbar(
            '成功',
            '买入条件已成功添加',
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Colors.green,
            colorText: Colors.white,
            duration: const Duration(seconds: 2),
          );
        } else {
          // 更新现有条件
          final companion = BuyConditionsCompanion(
            id: drift.Value(widget.condition!.id),
            conditionName: drift.Value(_nameController.text),
            listingDate: drift.Value(_listingDate),
            recentChange: _recentChangeController.text.isNotEmpty
                ? drift.Value(double.tryParse(_recentChangeController.text))
                : const drift.Value.absent(),
            eps: _epsController.text.isNotEmpty
                ? drift.Value(double.tryParse(_epsController.text))
                : const drift.Value.absent(),
            navps: _navpsController.text.isNotEmpty
                ? drift.Value(double.tryParse(_navpsController.text))
                : const drift.Value.absent(),
            capitalReserve: _capitalReserveController.text.isNotEmpty
                ? drift.Value(double.tryParse(_capitalReserveController.text))
                : const drift.Value.absent(),
            attentionLevel: _attentionLevelController.text.isNotEmpty
                ? drift.Value(int.tryParse(_attentionLevelController.text))
                : const drift.Value.absent(),
          );

          final updatedCondition = widget.condition!.copyWithCompanion(companion);
          await _controller.updateBuyCondition(updatedCondition);

          // 显示成功消息并立即关闭页面
          Get.back();
          Get.snackbar(
            '成功',
            '买入条件已成功更新',
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Colors.green,
            colorText: Colors.white,
            duration: const Duration(seconds: 2),
          );
        }
      } catch (e) {
        // 显示错误消息
        Get.snackbar(
          '错误',
          '操作失败: $e',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.red,
          colorText: Colors.white,
          duration: const Duration(seconds: 3),
        );
      } finally {
        _isLoading.value = false;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.condition == null ? '添加买入条件' : '编辑买入条件'),
        actions: [
          Obx(() => _isLoading.value
              ? const Padding(
            padding: EdgeInsets.all(16.0),
            child: SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(strokeWidth: 2),
            ),
          )
              : IconButton(
            icon: const Icon(Icons.save),
            onPressed: _saveCondition,
          )),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: ListView(
            children: [
              TextFormField(
                controller: _nameController,
                decoration: const InputDecoration(
                  labelText: '条件名称*',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入条件名称';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              // 上市时间选择器
              InkWell(
                onTap: () async {
                  final selectedDate = await showDatePicker(
                    context: context,
                    initialDate: _listingDate ?? DateTime.now(),
                    firstDate: DateTime(2000),
                    lastDate: DateTime(2100),
                  );
                  if (selectedDate != null) {
                    setState(() {
                      _listingDate = selectedDate;
                    });
                  }
                },
                child: InputDecorator(
                  decoration: const InputDecoration(
                    labelText: '上市时间',
                    border: OutlineInputBorder(),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        _listingDate != null
                            ? '${_listingDate!.year}-${_listingDate!.month.toString().padLeft(2, '0')}-${_listingDate!.day.toString().padLeft(2, '0')}'
                            : '选择日期',
                      ),
                      const Icon(Icons.calendar_today),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _recentChangeController,
                decoration: const InputDecoration(
                  labelText: '近期涨跌幅 (%)',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.number,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _epsController,
                decoration: const InputDecoration(
                  labelText: '每股收益',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.number,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _navpsController,
                decoration: const InputDecoration(
                  labelText: '每股净资产',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.number,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _capitalReserveController,
                decoration: const InputDecoration(
                  labelText: '资本公积金',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.number,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _attentionLevelController,
                decoration: const InputDecoration(
                  labelText: '关注级别 (1-5)',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value != null && value.isNotEmpty) {
                    final level = int.tryParse(value);
                    if (level == null || level < 1 || level > 5) {
                      return '请输入1-5之间的数字';
                    }
                  }
                  return null;
                },
              ),
              const SizedBox(height: 24),
              Obx(() => ElevatedButton(
                onPressed: _isLoading.value ? null : _saveCondition,
                child: _isLoading.value
                    ? const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(strokeWidth: 2),
                )
                    : Text(widget.condition == null ? '添加条件' : '更新条件'),
              )),
            ],
          ),
        ),
      ),
    );
  }
}